package com.cloud.translation.Adapter;

import android.speech.tts.TextToSpeech;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cloud.translation.BaseAdapter.BaseRecyclerAdapter;
import com.cloud.translation.BaseAdapter.BaseRecyclerHolder;
import com.cloud.translation.Dao.DaoUtils;
import com.cloud.translation.Model.BaseBean;
import com.cloud.translation.Model.Model;
import com.cloud.translation.R;
import com.cloud.translation.TTS.MyTTS;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HistoryAdapter extends BaseRecyclerAdapter<Model> {

    private MyTTS myTTS;

    private List<Language> languages;
    public HistoryAdapter(FragmentActivity activity) {
        super(activity, R.layout.item_history);
        myTTS = new MyTTS(activity);
        String[] languageString = activity.getResources().getStringArray(R.array.language);
        languages = new ArrayList<>();
        for (String language : languageString) {
            String[] str = language.split(",");
            Language bm = new Language();
            bm.setName(str[0]);
            bm.setAbbreviations(str[1]);
            languages.add(bm);
        }
    }

    @Override
    protected void convert(BaseRecyclerHolder holder, Model data) {
        holder.setText(R.id.content, data.getHistory());
        holder.setText(R.id.message, data.getResults());
        TextView textView = holder.getView(R.id.message);
        holder.getView(R.id.message_play).setOnClickListener(l -> {
            myTTS.mySpeak(textView.getText().toString());
        });
        holder.getView(R.id.message_delete).setOnClickListener(l -> {
            new DaoUtils(activity).delete(data);
            remove(items.indexOf(data));
        });
        TextView language1=holder.getView(R.id.language_1);
        TextView language2=holder.getView(R.id.language_2);
        language1.setText(data.getLanguage1());
        language1.setOnClickListener(l -> {
            OnLanguage(language1);
        });
        language2.setText(data.getLanguage2());
        language2.setOnClickListener(l -> {
            OnLanguage(language2);
        });
        holder.getView(R.id.message).setOnClickListener(l->{
            getResults(language1,language2, holder.getText(R.id.content), holder.getText(R.id.message));
        });
    }

    private void OnLanguage(TextView textView) {
        RecyclerView rv = new RecyclerView(activity);
        rv.setLayoutManager(new LinearLayoutManager(activity));
        PopupWindow popupWindow = new PopupWindow(rv, textView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
        HomeAdapter adapter = new HomeAdapter(activity, textView, popupWindow);
        rv.setAdapter(adapter);
        adapter.setData(languages);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(textView);
    }

    private void getResults(TextView language1,TextView language2,TextView textView,TextView message) {
        String languageCode = null,languageCode2 = null;
        for (Language language : languages) {
            if (language.getName().equals(language1.getText().toString())) {
                 languageCode = language.getAbbreviations();
            }
            if (language.getName().equals(language2.getText().toString())) {
                languageCode2 = language.getAbbreviations();
            }
        }
        getTr(languageCode,"ZH_CN",languageCode2,textView.getText().toString(),message);
    }

    private void getTr(String languageCode1,String middle,String languageCode2,String text,TextView message) {
        Request request = new Request.Builder()
                .url("https://fanyi.youdao.com/translate?&doctype=json&type=" + languageCode1 + "2" + languageCode2 + "&i=" +text )
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.toString();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Snackbar.make(message, "Save Fail", Snackbar.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String priceSting = response.body().string();
                try {
                    BaseBean body = gson.fromJson(priceSting, BaseBean.class);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String results = body.getTranslateResult().get(0).get(0).getTgt();
                            if (languageCode2.equals(middle)||languageCode1.equals("ZH_CN")) {
                                message.setText(results);
                            }else {
                                getTr(middle,languageCode2,languageCode2,results,message);
                            }
                        }
                    });
                } catch (Exception e) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Snackbar.make(message, "Save Fail", Snackbar.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

}
